package com.starpl.mobile.android.monthunsae.november.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.view.Menu;
import android.view.MenuItem;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.command.MonthUnsaeCommand;
import com.starpl.mobile.android.monthunsae.november.common.LoginUtil;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.common.ActivityUtil;
import com.starpl.mobile.android.platform.common.EmailUtil;
import com.starpl.mobile.android.platform.common.SharedUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.base.BaseSettingActivity;
import com.starpl.mobile.android.platform.common.network.HttpHandler;


/**
 * PreferenceActivity를 상속받아 구현한 설정 페이지
 * 
 * @author 우연화
 * @since 2011.03.16
 */
public class SettingActivity extends BaseSettingActivity implements OnPreferenceClickListener
{
	private Preference mPId;
	private Preference mPProfileImage;
	private Preference mPTimeSetting;
	
	private Preference mPVersion;
	private Preference mPHelpdesk;
	
	private CheckBoxPreference mCbMessage;
	private CheckBoxPreference mCbReply;
	private CheckBoxPreference mCbEvent;
	
	private int mPositionStartTime;
	private int mPositionEndTime;

	private String[] mStartTime =
	{
			"오전 0시", // 0
			"오전 1시", "오전 2시", "오전 3시", "오전 4시", "오전 5시", // 5
			"오전 6시", "오전 7시", "오전 8시", "오전 9시", "오전 10시", // 10
			"오전 11시",
			
			"오전 12시", "오후 1시", "오후 2시", "오후 3시", // 15
			"오후 4시", "오후 5시", "오후 6시", "오후 7시", "오후 8시", // 20
			"오후 9시", "오후 10시", "오후 11시" // 23
	};

	private String[] mEndTime =
	{
			"오전 1시", // 0
			"오전 2시", "오전 3시", "오전 4시", "오전 5시", "오전 6시", // 5
			"오전 7시", "오전 8시", "오전 9시", "오전 10시", "오전 11시", // 10

			"오전 12시", "오후 1시", "오후 2시", "오후 3시", "오후 4시", // 15
			"오후 5시", "오후 6시", "오후 7시", "오후 8시", "오후 9시", // 20
			"오후 10시", "오후 11시", "오후 12시" // 23
	};
	
	/* (non-Javadoc)
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.setting_activity);
		
		mPId = (Preference)findPreference("setting_activity_id");
		mPProfileImage = (Preference)findPreference("setting_activity_profile_image");
		mPTimeSetting = (Preference)findPreference("setting_activity_time");
		mPVersion = (Preference)findPreference("setting_activity_version");
		mPHelpdesk = (Preference)findPreference("setting_activity_profile_helpdesk");

		mCbMessage = (CheckBoxPreference)findPreference("setting_activity_message");
		mCbReply = (CheckBoxPreference)findPreference("setting_activity_reply");
		mCbEvent = (CheckBoxPreference)findPreference("setting_activity_event");
		
		mPId.setOnPreferenceClickListener(this);
		mPProfileImage.setOnPreferenceClickListener(this);
		mPTimeSetting.setOnPreferenceClickListener(this);
		mPHelpdesk.setOnPreferenceClickListener(this);
		
		mCbMessage.setOnPreferenceClickListener(this);
		mCbReply.setOnPreferenceClickListener(this);
		mCbEvent.setOnPreferenceClickListener(this);
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume()
	{
		super.onResume();
		
		setSettingValues();
		
		// TODO 유저정보 저장객체 application에 등록해 놓고 받아오기
		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
		
		mPId.setTitle(userInfo.getUserId()+" 로그아웃");
		
		try
		{
			String appsversion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			mPVersion.setTitle("버전 (" + appsversion + ")");
		}
		catch(NameNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause()
	{
		super.onPause();
		
		// TODO 서버에 갱신된 유저정보 보내기
	}

	private void setSettingValues()
	{
		// 설정값을 읽어와서 세팅한다.
		MonthUnsaeCommand.getConfiguration(new HttpHandler(this, "설정 값 가져오는 중")
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject data = ((JSONObject)result).getJSONObject("data");
					
					// 알람 시작 시간 및 종료시간 받아오기
					mPositionStartTime = data.getInt("pushStartTime");
					mPositionEndTime = data.getInt("pushEndTime") - 1;
					
					//  시작 시간 종료 시간 화면에 뿌리기
					mPTimeSetting.setSummary(mStartTime[mPositionStartTime] + " ~ " + mEndTime[mPositionEndTime]);

					// 서버에서 받아온 값으로 체크박스 설정
					mCbEvent.setChecked(data.getBoolean("event"));
					mCbMessage.setChecked(data.getBoolean("message"));
					mCbReply.setChecked(data.getBoolean("comment"));
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		});
	}
	
	/* (non-Javadoc)
	 * @see android.preference.Preference.OnPreferenceClickListener#onPreferenceClick(android.preference.Preference)
	 */
	@Override
	public boolean onPreferenceClick(Preference p)
	{
		// 유저 로그아웃
		if(p.getKey().equals("setting_activity_id"))
		{
			LoginUtil.logoutUser(this);
		}
		// 사용자 이미지 변경
		else if(p.getKey().equals("setting_activity_profile_image"))
		{
			startActivity(new Intent(SettingActivity.this, SettingProfileImageActivity.class));
		}
		else if(p.getKey().equals("setting_activity_time"))
		{
			Bundle extras = new Bundle();
			extras.putInt("startTime", mPositionStartTime);
			extras.putInt("endTime", mPositionEndTime);
			
			new ActivityUtil(this)
				.setTargetActivity(SettingAlarmActivity.class)
				.setRequestCode(17)
				.setBundle(extras)
				.show();
		}
		else if(p.getKey().equals("setting_activity_unsae"))
		{
			if (((CheckBoxPreference)p).isChecked())
			{
				SharedUtil.getInstance().putSharedPreference("unsaeAlarm", true);
			}
			else
			{
				SharedUtil.getInstance().putSharedPreference("unsaeAlarm", false);
			}
		}
		// 헬프 데스크에 이메일 보내기
		else if(p.getKey().equals("setting_activity_profile_helpdesk"))
		{
			UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
			String appsName = BaseApplication.getConfigPersistent("appsName");
			String nickName = userInfo.getNickName();
			String userId = userInfo.getUserId();
			String email = BaseApplication.getConfigPersistent("serviceEmail");
			EmailUtil.showHelpCenterEmail(email, appsName, nickName, userId);
		}
		else if(p.getKey().equals("setting_activity_message"))
		{
			changeCheckBox((CheckBoxPreference)p, "message");
		}
		else if(p.getKey().equals("setting_activity_reply"))
		{
			changeCheckBox((CheckBoxPreference)p, "comment");
		}
		else if(p.getKey().equals("setting_activity_event"))
		{
			changeCheckBox((CheckBoxPreference)p, "event");
		}
			
		return false;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		BaseApplication.getOptionMenu().onCreateOptionMenu(this, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		BaseApplication.getOptionMenu().onOptionsItemSelected(item);
		return false;
	}

	/**
	 * 푸시 설정을 변경합니다.
	 * 
	 * @param cbP 선택된 체크박스
	 * @param type 설정값
	 */
	private void changeCheckBox(CheckBoxPreference cbP, String type)
	{
		HttpHandler setConfigHandler = new HttpHandler(this, "푸시 설정 변경중")
		{
			@Override
			public void didSucceed(Object result)
			{
			}
		};
		
		if (cbP.isChecked())
		{
			MonthUnsaeCommand.setConfiguration(setConfigHandler, type, true);
		}
		else
		{
			MonthUnsaeCommand.setConfiguration(setConfigHandler, type, false);
		}
	}

	/* (non-Javadoc)
	 * @see android.preference.PreferenceActivity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode == RESULT_OK)
		{
			mPTimeSetting.setSummary(data.getStringExtra("startTime") + " ~ " + data.getStringExtra("endTime"));
		}
	}
}